<template>
	<div class="class-list table-theme">
		<head-title title="运营--定制分类列表"></head-title>
		<el-card>
			<div class="top-menu">
				<div class="menu-left">
					<select-view
						:option-list="statusList"
						:value="status"
						placeholder="上下架"
						type="status"
						@value="setSelectValue"
					>
					</select-view>
				</div>
				<div class="menu-right"> 
					<refresh-button @refresh="refreshPage"></refresh-button>
					<div class="add"><el-button type="primary" @click="add">添加分类</el-button></div>
				</div>
			</div>
			<p style="height:30px"></p>
			<el-table :data="classList" border stripe :tree-props="{children:'children'}" row-key="class_id" :default-expand-all="true">
				<el-table-column label="分类ID" align="center" prop="class_id"></el-table-column>
				<el-table-column label="分类名称" align="center">
                    <template slot-scope="scope">
                        <span v-html="scope.row.spl"></span>
                        {{scope.row.class_name}}
                    </template>
                </el-table-column>
				<el-table-column label="分类简称" align="center" prop="class_abbreviation"></el-table-column>
				<el-table-column label="分类图片" align="center" width="80">
					<template slot-scope="scope">
						<ImgPopover :src="scope.row.class_image"></ImgPopover>
					</template>
				</el-table-column>
				<el-table-column label="排序" align="center" prop="sort" width="180"></el-table-column>
				<el-table-column label="商品数量" align="center" prop="goods_count"></el-table-column>
				<el-table-column label="上下架" align="center" width="180">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.class_status" :active-value="1" :inactive-value="2" @change="upDown($event, scope.row.class_id)"></el-switch>
					</template>
				</el-table-column>
				<el-table-column label="添加时间" align="center" prop="add_time"></el-table-column>
				<el-table-column label="操作" align="center" width="200">
					<template slot-scope="scope">
                        <el-button type="primary" v-if="scope.row.class_p_id == 0" size="mini" @click="add(scope.row.class_id)">添加子分类</el-button>
						<el-button type="primary" size="mini" @click="edit(scope.row)">编辑</el-button>
						<el-button type="danger" size="mini" @click="del(scope.row.class_id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</el-card>

		<!-- 添加分类弹框 -->
		<el-dialog :title="title" :visible.sync="addDialog" width="500px" center :modal-append-to-body="false" @close="onClose">
			<el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="120px">
				<div class="class-info">
					<el-form-item label="图标:" class="upload-box" prop="class_name">
						<div class="iconImg">
							<el-upload
								class="avatar-uploader"
								ref="upload"
								action="fakeaction"
								:show-file-list="false"
								:http-request=" function(res) { return upload(res); } " multipleaccept="image/*" :on-change="ImgChange" > <img v-if="imageUrl" :src="imageUrl" class="avatar" />
								<i v-else class="el-icon-plus avatar-uploader-icon"></i>
							</el-upload>
						</div>
					</el-form-item>
					<div class="class-exhibition">
						<el-form-item label="分类名称:" prop="class_name"><el-input v-model="addForm.class_name" placeholder="请输入分类名称" clearable></el-input></el-form-item>
						<el-form-item label="排序:" prop="sort">
							<el-input
								type="number"
								onKeypress="return (/[\d]/.test(String.fromCharCode(event.keyCode)))"
								v-model="addForm.sort"
								placeholder="请输入排序"
								clearable
							></el-input>
						</el-form-item>
						<el-form-item label="分类简称:" prop="class_abbreviation">
							<el-input v-model="addForm.class_abbreviation" placeholder="请输入分类简称" clearable></el-input>
						</el-form-item>
						<el-form-item label="上下架:" prop="class_status">
							<el-switch v-model="addForm.class_status" :active-value="1" :inactive-value="2"></el-switch>
						</el-form-item>
					</div>
				</div>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="addDialog = false">取 消</el-button>
				<el-button type="primary" @click="submit('addForm')">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
import ImgPopover from '@/components/ImgPopover';
import SelectView from "@/components/SelectView";
export default {
	components: {
		ImgPopover,
		SelectView
	},
	data() {
		return {
			title: '添加分类',
			submitType: '', // 提交的类型 0 增加 1编辑
			imageUrl: '',
			addDialog: false,
			classList: [],
			status: 1,
			statusList: [
				{
					value: 1,
					label: '上架'
				},
				{
					value: 2,
					label: '下架'
				}
			],
			addForm: {
				class_name: '',
				class_image: '',
				sort: '',
				class_status: 1,
				is_customized:1,
                class_p_id:0,
                store_id:localStorage.getItem('store_id'),
				class_abbreviation:""
			},
			addFormRules: {
				class_name: [{ required: true, message: '请输入分类名称' }],
				class_image: [{ required: true, message: '请上传分类图标' }],
				class_status: [{ required: true, message: '上下架' }],
				sort: [{ required: true, message: '请输入排序' }]
			}
		};
	},
	watch: {
		'addForm.sort': function(val) {
			if (this.addForm.sort < 0) {
				this.addForm.sort = 0;
				this.$message.error('请输入正确的排序');
			}
		}
	},
	methods: {
		// 初始化列表
		init(e) {
			let data = {
				class_status: this.status,
				store_id: localStorage.getItem('store_id')
			};
			this.$http(this.$ApiList.CustomizedCategoryList, data).then(res => {
                const { list } = res.datas
                let data = [];
                list.forEach(item =>{
                    let children = [];
                    list.forEach(res=>{
                        if(res.class_p_id === item.class_id){
                            children.push(res);
                            item.children = children;
                        }
                    })
                    if(item.class_p_id == 0){
                        data.push(item);
                    }
                })
				this.classList = data;
			});
		},

		// 上下架
		upDown(e, class_id) {
			let data = {
				status: e,
				class_id: class_id
			};
			this.$http(this.$ApiList.CategoryDown, data).then(res => {
				if (res.code == 200) {
					this.$layer.msg('操作成功');
					this.init();
				}
			});
		},
		// 增加分类
		add(class_id) {
			this.title = '添加分类';
			this.addDialog = true;
            this.addForm.class_p_id = class_id || 0
		},
		onClose(){
			this.imageUrl = '';
			this.submitType = 0;
			this.addForm = {
				class_name: '',
				class_image: '',
				sort: '',
				class_status: 1,
				is_customized: 1,
                class_p_id:0,
				store_id: localStorage.getItem('store_id'),
				class_abbreviation:""
			};
			this.$refs['addForm'].resetFields();
			this.addDialog = false;
		},
		// 删除
		del(id) {
			this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					let data = {
						class_id: id
					};
					this.$http(this.$ApiList.CategoryDel, data).then(res => {
						if (res.code == 200) {
							this.$message({
								message: '删除成功',
								type: 'success'
							});
							this.init();
						}
					});
				})
				.catch(() => {});
		},
		// 编辑
		edit(content) {
			this.title = '编辑分类';
			this.submitType = 1;
			this.addForm = content;
            this.addForm.is_customized = 1
			this.imageUrl = content.class_image;
			this.addDialog = true;
		},
		// 上下架筛选
		statusSelect() {
			this.init();
		},
		// 刷新
		refreshPage() {
			this.status = 1;
			this.init();
		},
		// 图标上传
		upload(params) {
			//console.log(params);
			const file = params.file,
				fileType = file.type,
				isJPGPNG = file.type === 'image/jpeg' || 'image/png',
				isLt1MB = file.size / 1024 <= 1024;
			if (!isJPGPNG) {
				this.$message.error('只能上传图片格式png、jpg!');
				return;
			}
			if (!isLt1MB) {
				this.$message.error('图片不能大于1M');
				return;
			}

			this.addForm.class_image = new FormData();
			this.addForm.class_image.append('file[]', file);
		},
		// 转base64 本地预览
		ImgChange(file, fileList) {
			var event = event || window.event;
			var file = event.target.files[0];
			var reader = new FileReader();
			//转base64
			reader.onload = e => {
				this.imageUrl = e.target.result; //将图片路径赋值给src
			};
			reader.readAsDataURL(file);
		},
		submit(formName) {
			this.$refs[formName].validate(valid => {
				if (valid) {
					if (this.submitType == 0) {
						this.$http(this.$ApiList.publicUpload, this.addForm.class_image).then(res => {
							if (res.code == 200) {
								this.addForm.class_image = res.datas[0];
								this.$http(this.$ApiList.UpCategory, this.addForm).then(res => {
									if (res.code == 200) {
										this.$layer.msg('提交成功');
										this.addDialog = false;
										this.init();
									}
								});
							}
						});
					} else {
						if (this.imageUrl == this.addForm.class_image) {
							// 图片没变
							this.$http(this.$ApiList.UpdateCategory, this.addForm).then(res => {
								if (res.code == 200) {
									this.$layer.msg('编辑成功');
									this.addDialog = false;
									this.init();
								}
							});
						} else {
							this.$http(this.$ApiList.publicUpload, this.addForm.class_image).then(res => {
								if (res.code == 200) {
									this.addForm.class_image = res.datas[0];
									this.$http(this.$ApiList.UpdateCategory, this.addForm).then(res => {
										if (res.code == 200) {
											this.$layer.msg('编辑成功');
											this.addDialog = false;
											this.init();
										}
									});
								}
							});
						}
					}
				} else {
					this.$layer.msg('请填写完整信息后提交');
				}
			});
		},
		setSelectValue(obj){
				const{ type,value } = obj
				switch (type) {
					case 'status':
						this.status = value
						break;
				
					default:
						break;
				}
				this.init()
			}
	},
	created() {
		this.init();
	}
};
</script>
<style lang="scss" scoped>

</style>
